import { reactive } from "vue";
import type { FormRules } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

/** 自定义表单规则校验 */

// 修改表单时传入的id，用来跳过唯一性验证
let originalEventId: string | undefined;

// 设置原始事件ID的方法
export const setOriginalEventId = (id?: string) => {
  originalEventId = id;
  console.log("originalEventId", originalEventId);
};

export const formRules = reactive<FormRules>({
  name: [
    { required: true, message: "事件名称为必填项", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback();
          return;
        }
        // 如果原始事件ID存在且与当前值相同，则不进行唯一性验证
        if (originalEventId && originalEventId === value) {
          callback();
          return;
        }

        // 使用IIFE包装异步代码
        (async () => {
          try {
            const res = await http.get(
              changeHttpLink("/api/Common/check-unique"),
              {
                params: {
                  type: "event",
                  keyword: value,
                  excludeId: originalEventId ? originalEventId : undefined
                }
              }
            );
            // 添加类型断言以解决TypeScript类型检查问题
            const typedRes = res as {
              Success: boolean;
              Data?: boolean;
            };
            if (typedRes.Success && !typedRes.Data) {
              callback(new Error("事件名称已存在"));
            } else {
              callback();
            }
          } catch (error) {
            console.error(error);
            callback(new Error("验证事件名称失败，请重试"));
          }
        })();
      },
      trigger: "blur"
    }
  ],
  triggerCondition: [
    { required: true, message: "触发条件为必填项", trigger: "blur" }
  ],
  action: [{ required: true, message: "执行动作为必填项", trigger: "blur" }]
});
